//
//  HotCommentVC.m
//  AroundTheWorld
//
//  Created by IfelseGo on 16/5/24.
//  Copyright © 2016年 IfelseGo an. All rights reserved.
//

#import "HotCommentVC.h"
#import "DataHandler.h"
#import "HotCommentTableCell.h"
#import "HotCommentModel.h"
#import "HotCommentDataVC.h"
#import "HotCommentSeachTableCell.h"

#define WIDTH self.view.frame.size.width
#define HEIGHT self.view.frame.size.height

static NSString *const hotCommentReuse = @"hotCommentReuse";
static NSString *const hot_cityReuse = @"hot_cityReuse";
static NSString *const hot_citySerchReuse = @"hot_citySerchReuse";

typedef enum {Default, Search} DisplayMode;

@interface HotCommentVC ()<UISearchBarDelegate>
@property (nonatomic, strong) UITableView *myTabelView;
@property (nonatomic, assign) DisplayMode mode;
@end

@implementation HotCommentVC

- (void)viewDidLoad {
    [super viewDidLoad];
//    self.view.backgroundColor = [UIColor whiteColor];
    self.nextPage = 1;
    self.mode = Default;
    [self getData];
     self.searchArray = [NSMutableArray array];
    
    self.myTabelView = [[UITableView alloc] initWithFrame:CGRectMake(0, 50, WIDTH, HEIGHT - 140) style:UITableViewStylePlain];
    self.myTabelView.backgroundColor = [UIColor clearColor];
    self.myTabelView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:self.myTabelView];
    
    //成为代理人
    self.myTabelView.delegate = self;
    self.myTabelView.dataSource = self;
    
    //注册
    UINib *nib = [UINib nibWithNibName:@"HotCommentTableCell" bundle:[NSBundle mainBundle]];
    [self.myTabelView registerNib:nib forCellReuseIdentifier:hotCommentReuse];
    
    UINib *nib2 = [UINib nibWithNibName:@"HotCommentSeachTableCell" bundle:[NSBundle mainBundle]];
    [self.myTabelView registerNib:nib2 forCellReuseIdentifier:hot_citySerchReuse];
    
    //刷新
    [self refreshTests];
    
    //搜索
    [self loadSearchBar];
}
//data
-(void)getData{
    self.myArrayM = [NSMutableArray array];
    DataHandler *handler1 = [[DataHandler alloc] init];
    [handler1 getCommunityBase:self.nextPage SucceedHandler: ^(id result) {
        self.myArrayM = [NSMutableArray arrayWithArray:result];
        [self.myTabelView reloadData];
        } failedHandler:^(NSError *error) {
    }];
}

//cell高
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.mode == Default) {
        return 280;
    }else
    {
    return 130;
    }
}

//cell数
- (NSInteger )tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (self.mode == Default) {
        NSLog(@"self.search.count=========1===========%ld",self.myArrayM.count);
        return self.myArrayM.count;
    }else
    {
        NSLog(@"self.mya.count=========2===========%ld",self.searchArray.count);
        return self.searchArray.count;
    }
}

//建cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.mode == Search){
        HotCommentSeachTableCell *cell = [tableView dequeueReusableCellWithIdentifier:hot_citySerchReuse];
        HotCommentModel *model = [self.searchArray objectAtIndex:indexPath.row];
        cell.myModel = model;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
        
    }else
    {
        HotCommentTableCell *cell = [tableView dequeueReusableCellWithIdentifier:hotCommentReuse];
        HotCommentModel *model = [self.myArrayM objectAtIndex:indexPath.row];
        cell.myModel = model;
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
        HotCommentDataVC *hotVC = [[HotCommentDataVC alloc] init];
        HotCommentModel *model = [self.myArrayM objectAtIndex:indexPath.row];
        hotVC.myUrl = model.appview_url;
        //模态
        [self presentViewController:hotVC animated:YES completion:^{
         }];
}

//下拉刷新
- (void)refreshTests
{
    self.isUpLoading = NO;
    [self addHeader];
    [self addFooter];

}

#pragma mark --下拉刷新
- (void)addHeader
{
    __block HotCommentVC *vc = self;//因为block块里用self会报警告,所以需要将self声明成block变量
    
    // 添加下拉刷新头部控件
    [self.myTabelView addHeaderWithCallback:^{
        // 进入刷新状态就会回调这个Block
        vc.nextPage = 1;//记录页码的
        vc.isUpLoading = NO;//标记为下拉操作
        [vc GetPersonList:vc.nextPage];//重新请求数据
        
    }];
#pragma mark 自动刷新(一进入程序就下拉刷新)
    [self.myTabelView headerBeginRefreshing];
}

#pragma mark --上拉加载更多
- (void)addFooter
{
    __block HotCommentVC *vc = self;
    // 添加上拉刷新尾部控件
    [self.myTabelView addFooterWithCallback:^{
        // 进入刷新状态就会回调这个Block
        vc.nextPage ++;
        
        vc.isUpLoading = YES;//标记为上拉操作
        [vc GetPersonList:vc.nextPage];//请求数据
        NSLog(@"nextPage==============7=========%ld",vc.nextPage);
        if (vc.nextPage < 20) {
            [vc showAlert:[NSString stringWithFormat:@"刷新到第%ld页",vc.nextPage]];
        }else
        {
            [vc showAlert:@"已经到底部,没有可加载数据!"];
        }
    }];
}

#pragma mark --使用AFN进行数据请求
-(void)GetPersonList:(NSInteger)nextCursor
{
     if (self.isUpLoading == NO) {
        [self.myArrayM removeAllObjects];
    }
    DataHandler *handler = [[DataHandler alloc] init];
    NSLog(@"nextPage==============5=========%ld",self.nextPage);
     [handler getCommunityBase:self.nextPage SucceedHandler: ^(id result) {
         NSLog(@"nextPage==============6=========%ld",self.nextPage);
            NSMutableArray *arrayTemp = [NSMutableArray arrayWithArray:result];
            for (HotCommentModel *model in arrayTemp) {
                [self.myArrayM addObject:model];
            }
         [self.myTabelView footerEndRefreshing];
         [self.myTabelView headerEndRefreshing];
         [self.myTabelView reloadData];
        } failedHandler:^(NSError *error) {
            
        }];
}
     

//刷新后显示对话框
- (void)timerFireMethod:(NSTimer*)theTimer  //弹出框
{
    UIAlertView *promptAlert = (UIAlertView*)[theTimer userInfo];
    [promptAlert dismissWithClickedButtonIndex:0 animated:NO];
    promptAlert =NULL;
}

- (void)showAlert:(NSString *) _message{   //时间
    UIAlertView *promptAlert = [[UIAlertView alloc] initWithTitle:@"" message:_message delegate:nil cancelButtonTitle:nil otherButtonTitles:nil];
    
    [NSTimer scheduledTimerWithTimeInterval:1.5f
                                     target:self
                                   selector:@selector(timerFireMethod:)
                                   userInfo:promptAlert
                                    repeats:YES];
    [promptAlert show];
}



// Search Bar
- (void)loadSearchBar
{
    UISearchBar *searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 20, WIDTH, 30)];
    searchBar.placeholder = @"搜索目的地、帖子、特价、穷游er";
    
    searchBar.barTintColor = [UIColor whiteColor];
//    searchBar.barTintColor = DKColorPickerWithRGB(0xffffff,0xCFCFCF);
    searchBar.dk_backgroundColorPicker = DKColorPickerWithRGB(0xffffff,0xCFCFCF);
    searchBar.delegate = self;
    
    [self.view addSubview:searchBar];
    self.searchBar = searchBar;
}

- (void)addSearchButtonsWith:(NSArray *)hotList
{
    CGFloat margin = 15;
    CGFloat innerOffset = 40;
    CGSize  offset = CGSizeMake(20, 20);
    CGFloat buttonHeight = 30;
    CGFloat width = self.view.bounds.size.width - 2*margin;
    CGFloat maxX = self.view.bounds.size.width - margin;
    CGFloat x = margin;
    CGFloat y = 20;
    CGRect  frame = CGRectZero;
    
    // add hot label
    CGFloat labelHeight = 25;
    CGFloat separatorLineOffset = 8;
    CGFloat separatorLineHeight = 0.5;
    UIColor *separatorLineColor = [UIColor lightGrayColor];
    frame = CGRectMake(margin, y, width, labelHeight);
    UILabel *hotLabel = [[UILabel alloc] initWithFrame:frame];
    hotLabel.text = @"热门搜索";
    hotLabel.textColor = [UIColor grayColor];
    [self.searchMenu addSubview:hotLabel];
    
    y += (labelHeight + separatorLineOffset);
    frame = CGRectMake(margin, y, width, separatorLineHeight);
    UIView *hotLine = [[UIView alloc] initWithFrame:frame];
    hotLine.backgroundColor = separatorLineColor;
    [self.searchMenu addSubview:hotLine];
    
    // add hot buttons
    y += separatorLineOffset;
    UIFont *font = [UIFont systemFontOfSize:20];
    NSDictionary *attribute = @{NSFontAttributeName:font};
    
    for (NSInteger i = 0; i < hotList.count; i++) {
        NSString *title = [hotList objectAtIndex:i];
        CGSize size = [title sizeWithAttributes:attribute];
        
        CGFloat buttonWidth = size.width + innerOffset;
        
        CGRect frame = CGRectZero;
        if (x + buttonWidth > maxX) {
            x = margin;
            y += (offset.height + buttonHeight);
        }
        frame = CGRectMake(x, y, buttonWidth, buttonHeight);
        
        UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
        [button addTarget:self action:@selector(searchHotAction:) forControlEvents:UIControlEventTouchUpInside];
        button.layer.borderWidth = 1;
        button.layer.borderColor = [UIColor colorWithRed:0.282 green:0.780 blue:0.588 alpha:1.00].CGColor;
        button.layer.cornerRadius = buttonHeight/2;
        button.frame = frame;
        
        [button setTitle:title forState:UIControlStateNormal];
        [button setTitleColor:[UIColor grayColor] forState:UIControlStateNormal];
        [self.searchMenu addSubview:button];
        
        x += (offset.width + buttonWidth);
        //        size.width += innerOffset;
    }
}

- (void)searchHotAction:(UIButton *)button
{
    self.searchBar.text = button.titleLabel.text;
    
    [self removeSearchMenu];
    [self updateBySearch];
}

- (void)showSearchMenu
{
    self.searchBar.showsCancelButton = YES;
    CGRect originalFrame = CGRectMake(0, HEIGHT, WIDTH, HEIGHT);
    UIView *menu = [[UIView alloc] initWithFrame:originalFrame];
    menu.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:menu];
    self.searchMenu = menu;
    
    DataHandler *handler = [DataHandler new];
    [handler getSearchHistory:^(id result) {
        NSArray *list = (NSArray *)result;
        [self addSearchButtonsWith:list];
    } failedHandler:^(NSError *error) {
        
    }];
    
    [UIView animateWithDuration:0.4 animations:^{
        menu.frame = CGRectMake(0, 50, WIDTH, HEIGHT);
    } completion:^(BOOL finished) {
        [self.searchMenu becomeFirstResponder];
    }];
}

- (void)removeSearchMenu
{
    self.searchBar.showsCancelButton = NO;
    [self.searchBar resignFirstResponder];
    
    [self.searchMenu removeFromSuperview];
    self.searchMenu = nil;
}

- (void)updateBySearch
{
    self.mode = Search;
    [self removeSearchMenu];
    [self update];
}

- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar
{
    [self showSearchMenu];
    return YES;
}

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    [self updateBySearch];
}

- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
{
    [self removeSearchMenu];
    
    self.mode = Default;
    [self.myTabelView reloadData];
}

//搜索数据
-(void)update{
    
    NSString *searchString = [self.searchBar text];
    
    NSLog(@"===%@",searchString);
    [self.searchArray removeAllObjects];
    
    for (HotCommentModel *object in self.myArrayM) {
        NSString *title = object.title;
        if ([title rangeOfString:searchString].location != NSNotFound) {
            [self.searchArray addObject:object];
        }
    }
    [self.myTabelView reloadData];
//    DataHandler *handler1 = [[DataHandler alloc] init];
//    [handler1  getCommunityHotCommentSeachDataNotes:searchString SucceedHandler: ^(id result) {
//        self.searchArray = [NSMutableArray arrayWithArray:result];
//        [self.myTabelView reloadData];
//    } failedHandler:^(NSError *error) {
//    }];
    
    
//    [self.searchArray removeAllObjects];
//    for (HotCommentModel *movie in self.myArrayM) {
//        
//        //rangeOfString:方法是在movieName中搜索是否包含searchText
//        //rangeOfString 前面的参数是要被搜索的字符串，后面的是要搜索的字符
//        //NSNotFound 表示请求操作的某个内容没有发现
//        if ([movie.title rangeOfString:searchString].location != NSNotFound) {
//            
//            [self.searchArray addObject:movie];
//        }
//    }
//    NSLog(@"searchArray===%@",self.searchArray);
//     [self.myTabelView reloadData];
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
